package com.wzy.vx.redis;

import org.simpleframework.xml.core.Commit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @ProjectName: vx
 * @Package: com.wzy.vx.service
 * @ClassName: RedisLock
 * @Author: Administrator
 * @Description: ${description}
 * @Date: 2019/3/26 11:52
 * @Version: 1.0
 */
@Component
public class RedisLock {
    private  final  static Logger log = LoggerFactory.getLogger(RedisLock.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    //加锁
    public boolean lock(String key,String value){

        if (redisTemplate.opsForValue().setIfAbsent(key,value)){
            return  true;
        }
        //a b 同时访问
        String currentValid = redisTemplate.opsForValue().get(key);
        //如果锁过期
        if (!StringUtils.isEmpty(currentValid)
                && Long.parseLong(currentValid) < System.currentTimeMillis()){
            //获取上一个锁时间
            // A执获取锁后 B再次进来 由于currentValid一直是A getset获取的oldValue是B
            // A!=B所以B不能获得锁 保证了A.B只能有一人获取梭子
            String oldValue = redisTemplate.opsForValue().getAndSet(key,value);
            if (!StringUtils.isEmpty(oldValue) && oldValue.equals(currentValid)){
                return true;
            }
        }
        return false ;
    }

    //解锁
    public  void unlock(String key, String value){
        try {
            String currentValid = redisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(currentValid) && currentValid.equals(value)) {
                //删除key  相当于解锁
                redisTemplate.opsForValue().getOperations().delete(key);
            };
        }catch (Exception e){
            log.error("[redis分布式锁]解锁异常{}",e);
        }

    }



}
